import axios from "axios";
import qs from "qs";
import conf from '@/conf';
import $ from 'jquery';
import { Toast } from "vant";
import router from "@/router"

let loadingToast = [];


// 设置请求的路径前缀
axios.defaults.baseURL = conf.apiBaseUrl;

axios.interceptors.request.use(
    config => {
        var token = conf.getToken();
        if (token) {
            config.headers.authorization = 'Bearer ' + `${token}`
        }
        const loadingToastItem = Toast.loading({
            duration: 0,
            message: 'Loading...',
            forbidClick: true,
            loadingType: 'spinner',
        });
        loadingToast.push(loadingToastItem);
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        // 如果没有url，说明是上传图片的请求(这个自定义的)
        let res = null
        if (!response.config.url) {
            res = response
            if (res.status != 200) {
                Toast.fail({
                    message: res.message,
                    duration: 1000,
                    forbidClick: true,
                });
                return Promise.reject(res)
            }
        } else {
            res = response.data
            if (res.status != 200 && res.status != 1) {
                Toast.fail({
                    message: res.message,
                    duration: 1000,
                    forbidClick: true,
                });
                return Promise.reject(res)
            }
        }

        if (loadingToast.length > 0) {
            loadingToast.pop().clear();
        }
        return res;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    error.response.data.title &&
                        Toast.fail({
                            message: error.response.data.title,
                            forbidClick: true,
                        });
                    break;
                case 401:
                    router.push("/login");
                    localStorage.removeItem("otc_token")
                    localStorage.removeItem("userInfo")
                    break;
                case 405:
                    Toast.fail({
                        message: "Wrong HTTP request mode", //http请求方式有误
                        forbidClick: true,
                    });
                    break;
                case 500:
                    Toast.fail({
                        message: "Network Error",
                        forbidClick: true,
                    });
                    break;
                case 501:
                    Toast.fail({
                        message: "The server does not support a function required by the current request", //服务器不支持当前请求所需要的某个功能
                        forbidClick: true,
                    });
                    break;
            }
        } else {
            Toast.fail({
                message: 'Network Error',
                duration: 1000,
                forbidClick: true,
            });
        }
        if (loadingToast.length > 0) {
            setTimeout(() => {
                loadingToast.pop().clear();
            }, 1500)
        }
        return Promise.reject(error);
    }
);

// get
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

// post
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
            url: url,
            method: 'post',
            data: qs.stringify(params)
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function postjson(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            headers: { 'Content-Type': 'application/json;charset=utf-8' },
            url: url,
            method: 'post',
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function uploadFile(params = {}) {
    return new Promise((resolve, reject) => {
        axios({
            baseURL: process.env.VUE_APP_IMGUPLOAD,
            headers: {
                "Content-Type": "multipart/form-data",
            },
            url: '',
            method: 'post',
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default {
    get,
    post,
    postjson,
    uploadFile
};